﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using FBEntities.FBObjects;
using FBEntities.FBObjects.User;
using XDAFacebook;
using XFControls;
using XFControls.Utils;
using XFControls.XFPanels;
using XFControls.XFPanels.XFPanelItems;
using XFSenseUI.XFItems.SenseControls;
using System.Text.RegularExpressions;

#pragma warning disable 1591
namespace XFItemControls.XFPanels.XFPanelItems
{
    internal enum NotificationClick
    {
        Profile,
        Action
    }

    public class XFItemNotificationList : XFItemBase
    {
        private static int _pictureWidth = Settings.IconSize;
        private static int _lineSpace = 8;
        private readonly FBNotificationListObject _listObj;
        public SenseControlButton ReadButton = new SenseControlButton(Settings.LocalizationStrings.markAsRead);
        private NotificationClick _click;
        private int _height;
        //private FBPerson sender;

        public XFItemNotificationList(FBNotificationListObject listObj)
        {
            ReadButton.Style.Padding = 15;
            _listObj = listObj;
            _height = -1;
            //sender = FBPerson.GetPersonFromId(_listObj.sender_id.ToString());


            Style = new XFItemStyle
                        {
                            BackgroundColor = Color.White,
                            SelectedBackgroundColor = Color.Lavender,
                            TextFont = new Font(FontFamily.GenericSansSerif, 7.5f, FontStyle.Regular),
                            TextColor = Color.Navy,
                            SecondaryTextFont = new Font(FontFamily.GenericSansSerif, 7, FontStyle.Regular),
                            SecondaryTextColor = Color.Black,
                            DashStyleBottom = DashStyle.Solid,
                            BorderBottomColor = Color.DarkGray,
                            Padding = 5
                        };

            ItemType = XFItemType.Clickable;
        }

        public override int GetHeight()
        {
            if (_height > 0)
                return _height;

            int width = GetWidth();
            int buttonX = width - (Style.PaddingRight + ReadButton.ItemRectangle.Width + Style.PaddingLeft);
            int textWidth = buttonX - (Style.PaddingRight + (Style.PaddingLeft * 2) + _pictureWidth);
            int secondTextY = Style.PaddingTop + _lineSpace +
                              Style.TextFont.MeasureString(_listObj.title, new Rectangle(0, 0, textWidth, 0)).
                                  Height;

            int height = secondTextY +
                         Style.TextFont.MeasureString(_listObj.message, new Rectangle(0, 0, textWidth, 0)).Height;

            if (height < _pictureWidth)
                height = _pictureWidth + Style.PaddingTop;

            height += Style.PaddingBottom;

            using (var b = XFBitmapFactory.GetBitmap(1, 1))
            using (Graphics g = Graphics.FromImage(b))
                writeNotificationTime(Style.PaddingLeft, ref height, g);

            _height = height + Style.PaddingBottom;

            return _height;
        }

        public override void ResetHeight()
        {
            _height = -1;
        }

        public override void ItemPaint(Graphics g, int x, int y)
        {
            base.ItemPaint(g, x, y);
            int width = GetWidth();
            int buttonX = width - (Style.PaddingRight + ReadButton.ItemRectangle.Width + Style.PaddingLeft);
            int textWidth = buttonX - (Style.PaddingRight + (Style.PaddingLeft * 2) + _pictureWidth);
            int textX = (Style.PaddingLeft * 2) + _pictureWidth;

            //string url = sender.Picture.url;

            int secondTextY = Style.PaddingTop + _lineSpace +
                              g.DrawString(_listObj.title, new Rectangle(textX, Style.PaddingTop, textWidth, 0),
                                           Style);
            int height = secondTextY +
                         g.DrawString(_listObj.message, new Rectangle(textX, secondTextY, textWidth, 0), Style,
                                      Style.SecondaryTextFont, Style.SecondaryTextColor);

            if (height < _pictureWidth)
                height = _pictureWidth + Style.PaddingTop + Style.PaddingBottom;

            //this.DrawIcon(url, g, new Rectangle(Style.PaddingLeft, Style.PaddingTop, _pictureWidth, _pictureWidth));

            ReadButton.ItemPaint(g, buttonX, Style.PaddingTop);

            writeNotificationTime(Style.PaddingLeft, ref height, g);
        }

        public override void OnMouseDown(int x, int y)
        {
            base.OnMouseDown(x, y);
            int width = GetWidth();
            int buttonX = width - (Style.PaddingRight + ReadButton.ItemRectangle.Width + Style.PaddingLeft);

            if (x > buttonX && y < Style.PaddingTop + ReadButton.ItemRectangle.Height)
            {
                ReadButton.OnMouseDown(1, 1);
            }
            else if (x < Style.PaddingLeft + Style.PaddingRight + _pictureWidth)
                _click = NotificationClick.Profile;
            else
                _click = NotificationClick.Action;
        }

        public override void OnBlur()
        {
            base.OnBlur();
            ReadButton.OnBlur();
        }

        public override XFItemClickResult GetClickResult()
        {
            if (ReadButton.State == XFItemState.Selected)
                return ReadButton.GetClickResult();

            var reg = new Regex(@"(?:(?<type>groups)/(?<id>[0-9]+))|(?:(?<type>posts)/(?<id>[0-9]+))|(?:(?<type>story_fbid)=(?<id>[0-9]+))|(?:(?<type>(?<!story_)fbid)=(?<id>[0-9]+))|(?:(?<type>eid)=(?<id>[0-9]+))|(?:(?<type>sk)=(?<id>wall))");
            var regLinkId = new Regex(@"(?:(?<!fb)id)=(?<id>[0-9]+)(?:$|&)");

            string type = "";
            string id = "";
            if (_click == NotificationClick.Action)
            {
                var group = reg.Match(_listObj.link);
                type = group.Groups["type"].Value;
                id = group.Groups["id"].Value;
            }

            _listObj.MarkAsRead();

            switch (type)
            {
                case "Groups":  //  http://www.facebook.com/groups/(ID)/
                case "Likes":   //  http://www.facebook.com/photo.php?fbid=(ID)&set=p.(ID)&type=1
                case "Wall":    //  http://www.facebook.com/permalink.php?story_fbid=(ID)&id=(USERID)
                case "Feed Comments":   //  http://www.facebook.com/(PERSONLINK)/posts/(ID)
                case "Events":  //  http://www.facebook.com/event.php?eid=(ID)
                case "Photos":  //  http://www.facebook.com/photo.php?fbid=(ID)&set=p.(ID)&type=1
                    throw new Exception("Not Supported");

                case "groups":
                    {
                        if (Parent.Parent != null && Parent.Parent is XFPanelContainer)
                            ((XFPanelContainer)Parent.Parent).SetHeaderLeftButton(new XFButtonBack());

                        var post = new FBGroup { id = id };
                        post.Parse();
                        XFPanelList rp = XFItemControlUtils.SetupGroup(post);

                        Parent.SetRightPanel(rp);

                        rp.ShowAlphaBar(false);
                        rp.ShowScrollbar(true);
                        rp.ScrollbarColor = Parent.ScrollbarColor;
                    }
                    return XFItemClickResult.SlideLeft;
                case "fbid":
                    {
                        if (Parent.Parent != null && Parent.Parent is XFPanelContainer)
                            ((XFPanelContainer)Parent.Parent).SetHeaderLeftButton(new XFButtonBack());

                        var post = new FBPhoto { id = id };
                        post.Parse();
                        post.link = _listObj.link;
                        XFPanelList rp = XFItemPost.GetCommentsPanel(post.ToPost());

                        Parent.SetRightPanel(rp);

                        rp.ShowAlphaBar(false);
                        rp.ShowScrollbar(true);
                        rp.ScrollbarColor = Parent.ScrollbarColor;
                    }
                    return XFItemClickResult.SlideLeft;
                case "story_fbid":
                case "posts":
                    {
                        if (Parent.Parent != null && Parent.Parent is XFPanelContainer)
                            ((XFPanelContainer)Parent.Parent).SetHeaderLeftButton(new XFButtonBack());

                        if (type == "story_fbid")
                        {
                            var userId = regLinkId.Match(_listObj.link).Groups["id"].Value;
                            id = userId + "_" + id;
                        }

                        var post = new FBPost { id = id };
                        post.ParseGetUser();
                        XFPanelList rp = XFItemPost.GetCommentsPanel(post);

                        Parent.SetRightPanel(rp);

                        rp.ShowAlphaBar(false);
                        rp.ShowScrollbar(true);
                        rp.ScrollbarColor = Parent.ScrollbarColor;
                    }
                    return XFItemClickResult.SlideLeft;
                case "eid": //  TODO Later
                case "sk":  //  TODO Later
                default:
                    {
                        var friendProf = _listObj.from.ToPerson();

                        XFPanelList rp = XFItemControlUtils.SetupProfile(friendProf);

                        var back = new XFItemBackHeader();

                        if (Parent.Parent != null && Parent.Parent is XFPanelContainer)
                            ((XFPanelContainer)Parent.Parent).SetHeaderLeftButton(new XFButtonBack());

                        rp.AddHeaderItem(back);
                        Parent.SetRightPanel(rp);

                        rp.ShowAlphaBar(false);
                        rp.ShowScrollbar(true);
                    }
                    return XFItemClickResult.SlideLeft;
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            if (ReadButton != null)
                ReadButton.Dispose();

            ReadButton = null;
        }

        private void writeNotificationTime(int currX, ref int currY, Graphics g)
        {
            currX += _lineSpace;
            using (var b = new SolidBrush(Color.DarkSlateGray))
            {
                DateTime startTime = DateTime.UtcNow;
                DateTime endTime = _listObj.updated_time;
                TimeSpan span = startTime.Subtract(endTime);

                string display = "";
                if (span.Days > 0)
                {
                    display = span.Days == 1 ? span.Days + " Day ago" : span.Days + " Days ago";
                }
                else if (span.Hours > 0)
                {
                    display = span.Hours == 1 ? span.Hours + " Hour ago" : span.Hours + " Hours ago";
                }
                else if (span.Minutes > 0)
                {
                    display = span.Minutes == 1 ? span.Minutes + " Minute ago" : span.Minutes + " Minutes ago";
                }
                else if (span.Seconds > 0)
                {
                    display = span.Seconds == 1 ? span.Seconds + " Second ago" : span.Seconds + " Seconds ago";
                }
                else
                {
                    display = "Moments ago";
                }

                using (var f = new Font(Style.TextFont.Name, Style.TextFont.Size - 1, FontStyle.Bold))
                {
                    g.DrawString(display, f, b, currX, currY);
                    currY += _lineSpace + (int)g.MeasureString(display, f).Height;
                }
            }
        }
    }
}
#pragma warning restore 1591
